package cn.android_mobile.core;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Stack;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewStub;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.android_mobile.core.enums.CacheType;
import cn.android_mobile.core.enums.ModalDirection;
import cn.android_mobile.core.event.BasicEvent;
import cn.android_mobile.core.event.BasicEventDispatcher;
import cn.android_mobile.core.event.BasicEventDispatcher.IBasicListener;
import cn.android_mobile.core.net.BasicAsyncTask;
import cn.android_mobile.core.net.IBasicAsyncTask;
import cn.android_mobile.core.net.IBasicAsyncTaskFinish;
import cn.android_mobile.core.net.ThreadPool;
import cn.android_mobile.core.net.http.Service;
import cn.android_mobile.core.net.http.ServiceRequest;
import cn.android_mobile.core.ui.NavigationBar;
import cn.android_mobile.core.ui.listener.IMediaImageListener;
import cn.android_mobile.core.ui.listener.IMediaPicturesListener;
import cn.android_mobile.core.ui.listener.IMediaScannerListener;
import cn.android_mobile.core.ui.listener.IMediaSoundRecordListener;
import cn.android_mobile.core.ui.listener.IMediaVideoListener;
import cn.android_mobile.toolkit.CMDExecute;
import cn.android_mobile.toolkit.CacheUtil;
import cn.android_mobile.toolkit.Lg;
import cn.android_mobile.toolkit.ViewServer;

import com.google.gson.Gson;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.ArgbEvaluator;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.animation.ValueAnimator;
import com.umeng.analytics.MobclickAgent;
import com.ygsoft.smartfast.android.util.BitmapUtil;
import com.ygsoft.smartfast.android.util.CommonUI;
import com.ygsoft.smartfast.android.util.StringUtil;

@SuppressLint("NewApi")
public abstract class BasicActivity extends FragmentActivity implements IBasicAsyncTaskFinish, IBasicCoreMethod {
	public static String backText = "";
	private ProgressDialog progressDialog;// 加载进度条
	protected ActivityManager activityManager;
	protected DisplayMetrics metrics;
	public InputMethodManager imm;// 键盘管理
	public RelativeLayout rootView;// 根容器
	public BasicApplication application;
	public float SCREEN_WIDTH; // 设备屏幕宽
	public float SCREEN_HEIGHT;// 设备屏幕高
	public NavigationBar navigationBar;
	private LinearLayout progressBar;
	private long _firstTime = 0;
	private ArrayList<BasicAsyncTask> tasks = new ArrayList<BasicAsyncTask>();
	private ViewStub bodyStub;

	protected BasicListener listener;
	public boolean fragmentChangeEffect = false;
	protected int fragmentBodyLayoutRes = -1;
	public LayoutInflater inflater;
	protected Gson g = new Gson();

	private float widthDip = 0;
	private ModalDirection direction = ModalDirection.RIGHT;
	private RelativeLayout helpView;// 帮助页面 浮动 第一次运行展现，点击 关闭

	// 拍照标志
	private static final int PHOTO_REQUEST_TAKEPHOTO = 801;
	// 裁剪结果的值
	private static final int PHOTO_REQUEST_CUT = 803;
	/**
	 * 路径.
	 */
	private File tempFile;

	/**
	 * 配置 是否在Fragment 切换的时候 需要默认动画
	 * 
	 * @param flag
	 */
	public void isDisplayFragmentEffect(boolean flag) {
		fragmentChangeEffect = flag;
	}

	/**
	 * 是否在 调用接口的时候显示加载进度条
	 * 
	 * @param b
	 */
	public void isDisplayProgressByHttpRequest(boolean b) {
		BasicAsyncTask.asyncWithProgress = b;
	}

	@Override
	public void async(IBasicAsyncTask callback, String interfaceName, CacheType cacheType, Object... params) {
		closeSoftInput();
		closeViewInteraction();
		if (BasicAsyncTask.asyncWithProgress) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					displayProgressBar();
				}
			});
		}
		BasicAsyncTask task = new BasicAsyncTask(callback, interfaceName, cacheType);
		tasks.add(task);
		task.addFinishListener(this);
		task.execute(params);
	}

	@Override
	public void async(IBasicAsyncTask callback, String interfaceName, Object... params) {
		async(callback, interfaceName, CacheType.BASIC_NET, params);
	}

	@Override
	public void async(IBasicAsyncTask callback, ServiceRequest req, Service service, CacheType cacheType) {
		closeSoftInput();
		closeViewInteraction();
		if (BasicAsyncTask.asyncWithProgress) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					displayProgressBar();
				}
			});
		}
		BasicAsyncTask task = new BasicAsyncTask(req, service, cacheType, callback);
		tasks.add(task);
		task.addFinishListener(this);
		task.execute();
	}

	@Override
	public void async(IBasicAsyncTask callback, ServiceRequest req, Service service) {
		async(callback, req, service, CacheType.DEFAULT_NET);
	}

	/**
	 * 清理 EditText
	 * 
	 * @param et
	 * @param clear
	 * @param clearOnce
	 */
	public void setEditViewClearButton(final EditText et, final View clear) {
		setEditViewClearButton(et, clear, true);
	}

	public void setEditViewClearButton(final EditText et, final View clear, final boolean clearOnce) {

		et.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (et.getText().toString().trim().length() == 0) {
					clear.setVisibility(View.GONE);
				} else {
					clear.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		clear.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (clearOnce) {
					et.setText("");
				} else {
					String regPhoneNum = et.getText().toString().trim();
					if (regPhoneNum.length() > 0) {
						regPhoneNum = regPhoneNum.substring(0, regPhoneNum.length() - 1);
						et.setText(regPhoneNum);
						// 设置edittext编辑在末尾
						CharSequence text = et.getText();
						if (text instanceof Spannable) {
							Spannable spanText = (Spannable) text;
							Selection.setSelection(spanText, text.length());
						}
					}
				}
			}
		});

	}

	/**
	 * 异步运行完成后 从tasks 任务管理中移除
	 */
	@Override
	public void asyncTaskFinish(BasicAsyncTask task) {
		tasks.remove(task);
		openViewInteraction();
		if (BasicAsyncTask.asyncWithProgress && tasks.size() == 0) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					hiddenProgressBar();
				}
			});
		}
		// Lg.print("TaskFinish-> size:" + tasks.size());
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		SCREEN_WIDTH = metrics.widthPixels;
		SCREEN_HEIGHT = metrics.heightPixels;
		imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		activityManager = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);
		// 设置全局的handler
		application = (BasicApplication) this.getApplication();
		if (!isNetworkAvailable()) {
			// showDialog(R.id.application_dialog_net_error);
			// toast("网络连接失败");
			showDialog("", "网络连接失败", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					popActivity();
				}
			}, false);
		}

		BasicApplication.activityStack.add(this);
		fm = getSupportFragmentManager();
		inflater = getLayoutInflater();
		super.onCreate(savedInstanceState);
		if (Lg.DEBUG) {
			ViewServer.get(this).addWindow(this);
		}
	}

	public Handler handler = new Handler() {
	};
	private RelativeLayout modalViewGroup; // 用来动画 模态显示的 容器，里面可以嵌套fragment
	private RelativeLayout modalViewGroupBg;// 用来动画 模态显示的 背景遮罩层
	private TextView progressBarLabel;

	@Override
	public Bitmap takeScreenshot(View view) {
		assert view.getWidth() > 0 && view.getHeight() > 0;
		Bitmap.Config config = Bitmap.Config.ARGB_8888;
		Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), config);
		Canvas canvas = new Canvas(bitmap);
		view.draw(canvas);
		return bitmap;
	}

	@Override
	public void setContentView(int layoutResID) {
		super.setContentView(R.layout.activity_frame);
		navigationBar = new NavigationBar(this, (ViewStub) findViewById(R.id.title_stub));
		progressBar = (LinearLayout) findViewById(R.id.frame_progress);
		progressBarLabel = (TextView) findViewById(R.id.frame_progress_label);
		modalViewGroup = (RelativeLayout) findViewById(R.id.frame_modal_view_root);
		helpView = (RelativeLayout) findViewById(R.id.frame_help_relativelayout);
		modalViewGroupBg = (RelativeLayout) findViewById(R.id.frame_modal_view_bg);
		modalViewGroupBg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				popModalFragment();
			}
		});

		helpView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (_tmpBtmp != null && !_tmpBtmp.isRecycled()) {
					_tmpBtmp.recycle();
				}
				if (helpImgs.size() > 0) {
					_tmpBtmp = displayHelpView(helpImgs.pop());
				} else if (helpFragmentImgs.size() > 0) {
					_tmpBtmp = displayHelpView(helpFragmentImgs.pop());
				} else {
					helpView.setVisibility(View.GONE);
				}
			}
		});
		bodyStub = (ViewStub) findViewById(R.id.body_stub);
		bodyStub.setLayoutResource(layoutResID);
		bodyView = bodyStub.inflate();
		rootView = (RelativeLayout) findViewById(R.id.main_root);
		// 换肤功能
		skinColor = CacheUtil.getInteger("SKIN_COLOR");
		if (skinColor != -1) {
			navigationBar.layout.setBackgroundColor(skinColor);
			// bodyView.setBackgroundColor(skinColor);
		}
		initDefault();
		init();
	}

	Bitmap _tmpBtmp = null;;

	/**
	 * 屏蔽左边返回按钮的文字
	 */
	protected void initDefault() {
		/*if (backActivityTitle.equals("")) {
			navigationBar.leftBtn.setVisibility(View.GONE);
		} else {*/
			navigationBar.leftBtn.setVisibility(View.VISIBLE);
//			navigationBar.leftBtn.setText(" " + backActivityTitle);
			navigationBar.leftBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// BasicActivity.this.finish();
					popFragment();
				}
			});
//		}
		navigationBar.rightBtn.setVisibility(View.GONE);
	}

	public void displayProgressBar() {
		progressBar.bringToFront();
		progressBar.setVisibility(View.VISIBLE);
		progressBarLabel.setVisibility(View.GONE);
	}

	@Override
	public void displayProgressBar(String s) {
		// Lg.print("public void displayProgressBar(String s) ");
		progressBar.bringToFront();
		progressBar.setVisibility(View.VISIBLE);
		progressBarLabel.setVisibility(View.VISIBLE);
		progressBarLabel.setText(s);
	}

	public void hiddenProgressBar() {
		progressBar.setVisibility(View.GONE);
		progressBarLabel.setVisibility(View.GONE);
		progressBarLabel.setText("");
	}

	/**
	 * 显示进度条
	 */
	public void showProgress() {
		showProgress(R.string.loading_net, true);
	}

	public void showProgress(boolean canBack) {
		showProgress(R.string.loading_net, canBack);
	}

	/**
	 * 显示进度条
	 * 
	 * @param resID
	 * @param canBack
	 */
	public void showProgress(int resID, boolean canBack) {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
			progressDialog.cancel();
		}
		progressDialog = ProgressDialog.show(this, "", getResources().getString(resID));
		progressDialog.setCancelable(canBack);
	}

	/**
	 * 显示进度条
	 * 
	 * @param res
	 * @param canBack
	 */
	public void showProgress(String res, boolean canBack) {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog.cancel();
		}
		progressDialog = ProgressDialog.show(this, "", res);
		progressDialog.setCancelable(canBack);
	}

	/**
	 * 取消进度条
	 */
	public void cancelProgress() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog.cancel();
		}
	}

	public void cancelAllTask() {
		if (tasks == null || tasks.size() == 0)
			return;
		for (int i = 0; i < tasks.size(); i++) {
			cancelAsyncTask(tasks.get(i));
		}
		tasks.clear();
		// Lg.println("cancelAllTask() current tasks:" + tasks.size(), true);
	}

	@Override
	public void finish() {
		// Lg.print(this + " finish()");
		cancelAllTask();
		removeBasicEvent();
		super.finish();
	}

	protected void init() {
		initComp();
		initListener();
		initData();
	}

	protected abstract void initComp();

	protected abstract void initListener();

	protected abstract void initData();

	public boolean isEmpty(Object obj) {
		boolean f = false;
		if (obj == null) {
			f = true;
		} else if (obj instanceof TextView) {
			TextView tv = (TextView) obj;
			if (TextUtils.isEmpty(tv.getText())) {
				f = true;
			}
		} else if (obj instanceof EditText) {
			EditText et = (EditText) obj;
			if (TextUtils.isEmpty(et.getText())) {
				f = true;
			}
		} else if (obj instanceof String) {
			String s = (String) obj;
			if (s.trim().equals("")) {
				f = true;
			}
		}
		return f;
	}

	/**
	 * 退出应用
	 */
	public void exitApp() {
		long secondTime = System.currentTimeMillis();
		if (secondTime - _firstTime > 2000) {// 如果两次按键时间间隔大于2000毫秒，则不退出
			toast("再按一次退出程序...");
			_firstTime = secondTime;// 更新firstTime
			return;
		} else {
			exitAppWithToast();
		}
	}

	public void exitAppWithToast() {
		// SPUtil.saveObject("CAR_LIST", HomeModule.getInstance().carnumList,
		// SPUtil.CAR_CACHE);
		// ActivityManager activityManager = (ActivityManager)
		// getSystemService(ACTIVITY_SERVICE);
		// activityManager.restartPackage(getPackageName());
		// activityManager.killBackgroundProcesses(getPackageName());
		CacheUtil.saveInteger("app_help_view", 100);
		ThreadPool.basicPool.shutdown();
		ThreadPool.fixedPool.shutdown();
		while (BasicApplication.activityStack.size() > 0) {
			BasicApplication.activityStack.pop().finish();
		}
		finish();
		System.gc();
		System.exit(0);
	}
	
	/**
	 * 除了要保留的页面之外，关闭其他页面
	 * @param whiseActivityName 需要保留的页面的名称
	 */
	public void closeOtherActivity(String whiseActivityName) {
		for (int i = 0; i < BasicApplication.activityStack.size(); i++) {
			String contextString = BasicApplication.activityStack.get(i)
					.toString();
			String activityName = contextString.substring(
					contextString.lastIndexOf(".") + 1,
					contextString.indexOf("@"));
			// 判断不是首页就关闭
			if (!activityName.equals(whiseActivityName)) {
				BasicApplication.activityStack.pop().finish();
			}
		}
	}
	// 关闭软键盘
	public void closeSoftInput() {
		if (imm != null && imm.isActive()) {
			View focusView = getCurrentFocus();
			if (focusView != null) {
				imm.hideSoftInputFromWindow(focusView.getWindowToken(), 0);
			}
		}
	}

	public void showSoftInput(EditText et) {
		imm.showSoftInput(et, 0);
	}

	/**
	 * 获取当前程序的版本号 　　
	 */
	public int getVersionCode() {
		// 获取packagemanager的实例
		PackageManager packageManager = getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = null;
		try {
			packInfo = packageManager.getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return packInfo.versionCode;
	}

	// 取消异步调用
	public void cancelAsyncTask(BasicAsyncTask task) {
		if (task != null && task.isCancelled() == false) {
			task.abort();
			task.cancel(true);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			if (isModalFragmentDisplay) {
				popModalFragment();
			} else {
				popActivity();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/** 
	 * 上滑选择器是否显示，显示时按BACK键将是下滑消失，否则执行super.onKeyDown
	 * @return
	 */
	public boolean isModalFragmentDisplay() {
		return isModalFragmentDisplay;
	}

	/**
	 *  根据文字资源文件显示Toast。
	 * {@inheritDoc}
	 * @see cn.android_mobile.core.IBasicCoreMethod#toast(int)
	 */
	public void toast(int resId) {
		CommonUI.showToast(getActivity(), resId);
	}

	/**
	 *  根据文字文件显示Toast。
	 * {@inheritDoc}
	 * @see cn.android_mobile.core.IBasicCoreMethod#toast(java.lang.String)
	 */
	public void toast(String text) {
		CommonUI.showToast(getActivity(), text);
	}

	/**
	 * 意见反馈 邮件发送
	 * */
	public void sendMailByIntent(String msg, String email) {
		Intent data = new Intent(Intent.ACTION_SENDTO);
		data.setData(Uri.parse("mailto:" + email));// 收件人
		// data.putExtra(Intent.EXTRA_EMAIL, new
		// String[]{"fyygw10@126.com"});//更多的收件人
		// data.putExtra(Intent.EXTRA_CC, new
		// String[]{"zhenfang@wistronits.com"});//抄送
		// data.putExtra(Intent.EXTRA_BCC, new
		// String[]{"fangyygw@gmail.com"});//秘密发送
		data.putExtra(Intent.EXTRA_SUBJECT, "[意见反馈]");
		data.putExtra(Intent.EXTRA_TEXT, msg);
		startActivity(data);
	}

	/**
	 * 检测网络连接是否可用
	 * 
	 * @param ctx
	 * @return true 可用; false 不可用
	 */
	public boolean isNetworkAvailable() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null) {
			return false;
		}
		NetworkInfo[] netinfo = cm.getAllNetworkInfo();
		if (netinfo == null) {
			return false;
		}
		for (int i = 0; i < netinfo.length; i++) {
			if (netinfo[i].isConnected()) {
				return true;
			}
		}
		return false;
	}

	public int dip2px(float dipValue) {
		final float scale = this.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	public int px2dip(float pxValue) {
		final float scale = this.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * @note 获取该activity所有view
	 * @author liuh
	 * */
	public List<View> getAllChildViews() {
		View view = this.getWindow().getDecorView();
		return getAllChildViews(view);
	}

	public List<View> getAllChildViews(View view) {
		List<View> allchildren = new ArrayList<View>();
		if (view instanceof ViewGroup) {
			ViewGroup vp = (ViewGroup) view;
			for (int i = 0; i < vp.getChildCount(); i++) {
				View viewchild = vp.getChildAt(i);
				// Lg.print(viewchild);
				allchildren.add(viewchild);
				allchildren.addAll(getAllChildViews(viewchild));
			}
		}
		// Lg.print("--------");
		return allchildren;
	}

	/* 显示Dialog的method */
	protected Builder dialog;

	public Builder createDialog() {
		if (dialog == null) {
			dialog = new AlertDialog.Builder(this);
		} else {
			return dialog;
		}
		return dialog;
	}

	@Override
	public void showDialog(String title, String mess) {
		createDialog().setTitle(title).setMessage(mess).setNegativeButton("确定", null).show();
	}

	@Override
	public void showDialog(String title, String mess, DialogInterface.OnClickListener clickListener,
			DialogInterface.OnClickListener cancelListener, boolean cancelable) {
		createDialog().setTitle(title).setMessage(mess).setPositiveButton("确定", clickListener)
				.setNegativeButton("取消", cancelListener).setCancelable(cancelable).show();
	}

	@Override
	public void showDialog(String title, String mess, DialogInterface.OnClickListener clickListener,
			DialogInterface.OnClickListener cancelListener) {
		showDialog(title, mess, clickListener, cancelListener, true);
	}

	@Override
	public void showDialog(String title, String mess, DialogInterface.OnClickListener clickListener, boolean cancelable) {
		createDialog().setTitle(title).setMessage(mess).setPositiveButton("确定", clickListener)
				.setCancelable(cancelable).show();
	}

	public void showDialog(String mess) {
		createDialog().setMessage(mess).setNegativeButton("确定", null).show();
	}

	// private static final int RESULT_CAPTURE_IMAGE = 1;// 照相的requestCode
	private static final int REQUEST_CODE_TAKE_VIDEO = 2;// 摄像的照相的requestCode
	private static final int RESULT_CAPTURE_RECORDER_SOUND = 3;// 录音的requestCode
	private static final int RESULT_CAPTURE_PICTURES = 4;// 本地相冊
	private static final int RESULT_SCANNER = 5;// 条码扫描
	// private static final int RESULT_CAPTURE_CROP = 8;// 裁剪
	// private String strImgPath = "";// 照片文件绝对路径
	private String strVideoPath = "";// 视频文件的绝对路径
	private String strRecorderPath = "";// 录音文件的绝对路径
	private IMediaImageListener iMediaImageListener = null;
	private IMediaVideoListener iMediaVideoListener = null;
	private IMediaSoundRecordListener iMediaSoundRecordListener = null;
	private IMediaPicturesListener iMediaPicturesListener = null;
	private IMediaScannerListener iMediaScannerListener = null;
	public FragmentManager fm;
//	public BasicFragment currentFragment;

	public void addMediaImageListener(IMediaImageListener listener) {
		this.iMediaImageListener = listener;
	}

	public void addMediaPictureListener(IMediaPicturesListener listener) {
		this.iMediaPicturesListener = listener;
	}

	public void addMediaScannerListener(IMediaScannerListener listener) {
		this.iMediaScannerListener = listener;
	}

	public void addMediaVideoListener(IMediaVideoListener listener) {
		this.iMediaVideoListener = listener;
	}

	public void addMediaSoundRecordListener(IMediaSoundRecordListener listener) {
		this.iMediaSoundRecordListener = listener;
	}

	/**
	 * 本地相册
	 */
	public void startPictures() {
		tempFile = new File(Environment.getExternalStorageDirectory(), FileUtil.getNowPhotoFileName());
		Intent getAlbum = new Intent(Intent.ACTION_PICK);
		getAlbum.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
		// getAlbum.setType("image/*");
		startActivityForResult(getAlbum, RESULT_CAPTURE_PICTURES);
	}

	/**
	 * 本地相册
	 */
	public void startPictures(int w, int h) {
		startPictures();
		this.outputX = w;
		this.outputY = h;
	}

	/**
	 * 作者：shaorulong 裁剪图片，比例为1:1
	 * 
	 * @param uri
	 */
	private void startPhotoZoomLong(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// crop为true是设置在开启的intent中设置显示的view可以剪裁
		intent.putExtra("crop", "true");

		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);

		// outputX,outputY 是剪裁图片的宽高
		intent.putExtra("outputX", outputX);
		intent.putExtra("outputY", outputY);
		intent.putExtra("return-data", true);
		intent.putExtra("noFaceDetection", true);
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	// 需要裁剪的图片的宽度
	private int outputX = 300;
	// 需要裁剪的图片的高度
	private int outputY = 300;

	/**
	 * 照相功能
	 */
	public void startCamera(int w, int h) {
		startCamera();
		this.outputX = w;
		this.outputY = h;
	}

	/**
	 * 照相功能
	 */
	public void startCamera() {
		tempFile = new File(Environment.getExternalStorageDirectory(), FileUtil.getNowPhotoFileName());

		Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// 指定调用相机拍照后照片的储存路径
		cameraintent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
		startActivityForResult(cameraintent, PHOTO_REQUEST_TAKEPHOTO);

	}

	/**
	 * 拍摄视频
	 */
	public void startVideo() {
		Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
		startActivityForResult(intent, REQUEST_CODE_TAKE_VIDEO);
	}

	/**
	 * 录音功能
	 */
	public void startSoundRecorder() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("audio/amr");
		startActivityForResult(intent, RESULT_CAPTURE_RECORDER_SOUND);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// Lg.print("onActivityResult+ fragment");
		switch (requestCode) {
		case PHOTO_REQUEST_TAKEPHOTO:// 当选择拍照时调用
			// 当需要裁剪的时候才进行裁剪操作，否则不用裁剪
			if (PhotoTypeModule.getInstance().isNeetToCut()) {
				// 需要剪切的跳转过去剪切界面
				startPhotoZoomLong(Uri.fromFile(tempFile));
			} else {
				// 不需要进行裁剪的操作
				if (iMediaImageListener != null && tempFile != null && StringUtil.isNotEmptyString(tempFile.getAbsolutePath())) {
					// 压缩操作放到上传页面进行
					// myImageCompress(tempFile.getAbsolutePath());
					iMediaImageListener.mediaImagePath(tempFile.getAbsolutePath());
				}

			}
			break;

		case PHOTO_REQUEST_CUT:// 裁剪的时候返回的结果
			if (data != null)
				// setPicToView(data);
				sentPicToNext(data);
			break;

		case BasicActivity.RESULT_CAPTURE_PICTURES:// 相册
			if (resultCode == RESULT_OK) {
				// 图片的uri
				Uri selectedImage = data.getData();
				// 当需要裁剪的时候才进行裁剪操作，否则不用裁剪
				if (PhotoTypeModule.getInstance().isNeetToCut()) {
					// 需要剪切的跳转过去剪切界面
					startPhotoZoomLong(selectedImage);
				} else {

					if (iMediaPicturesListener != null) {

						if (selectedImage != null) {
							String uriStr = selectedImage.toString();
							String path = uriStr.substring(10, uriStr.length());
							if (path.startsWith("com.sec.android.gallery3d")) {
								// "It's auto backup pic path:"+selectedImage.toString());
								return;
							}

							String[] filePathColumn = { MediaStore.Images.Media.DATA };
							Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
							cursor.moveToFirst();
							int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
							String picturePath = cursor.getString(columnIndex);
							cursor.close();
							iMediaPicturesListener.mediaPicturePath(picturePath);
						}

					}
				}
			}
			break;

		case BasicActivity.REQUEST_CODE_TAKE_VIDEO:// 拍摄视频
			if (resultCode == RESULT_OK) {
				Uri uriVideo = data.getData();
				Cursor cursor = getContentResolver().query(uriVideo, null, null, null, null);
				if (cursor.moveToNext()) {
					/** _data：文件的绝对路径 ，_display_name：文件名 */
					strVideoPath = cursor.getString(cursor.getColumnIndex("_data"));
					// showToast(strVideoPath);
					if (iMediaVideoListener != null) {
						iMediaVideoListener.mediaVideoPath(strVideoPath);
					}
				}
			}
			break;
		case BasicActivity.RESULT_CAPTURE_RECORDER_SOUND:// 录音
			if (resultCode == RESULT_OK) {
				Uri uriRecorder = data.getData();
				Cursor cursor = getContentResolver().query(uriRecorder, null, null, null, null);
				if (cursor.moveToNext()) {
					/** _data：文件的绝对路径 ，_display_name：文件名 */
					strRecorderPath = cursor.getString(cursor.getColumnIndex("_data"));
					// showToast(strRecorderPath);
					if (iMediaSoundRecordListener != null) {
						iMediaSoundRecordListener.mediaSoundRecordPath(strRecorderPath);
					}
				}
			}
			break;
		case BasicActivity.RESULT_SCANNER:// 拍照
			if (resultCode == RESULT_OK) {
				if (iMediaScannerListener != null) {
					iMediaScannerListener.mediaScannerResult(data.getStringExtra("result"));
				}
			}
			break;
		}
	}

	// 将进行剪裁后的图片传递到下一个界面上
	private void sentPicToNext(Intent picdata) {
		Bundle bundle = picdata.getExtras();
		if (bundle != null) {
			Bitmap photo = bundle.getParcelable("data");
			if (photo != null) {
				// 保存图片
				FileUtil.saveBitmap(photo, tempFile.getAbsolutePath());
				if (iMediaImageListener != null) {
					// 压缩操作放到上传页面进行
					// myImageCompress(tempFile.getAbsolutePath());
					iMediaImageListener.mediaImagePath(tempFile.getAbsolutePath());
				}
				// imageView.setImageResource(R.drawable.user_default_icon);
			}

		}
	}

	/**
	 * 按像素图片压缩，最大为512KB。 2014-11-19 shaorulong修改，修改内容为： 不再对图片源进行缩放，采用BitmapUtil.getBitmapFromFile获取图片源进行图片质量的压缩，最大为512kb
	 * 
	 * @param strImgPath
	 *            图片路径
	 */
	public Bitmap myImageCompress(String strImgPath) {
		// Bitmap bmp = myReduceImage(strImgPath);
		Bitmap bmp = BitmapUtil.getBitmapFromFile(strImgPath, getActivity());
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int options = 100;//
		bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
		// 把图片的质量由最小控制在十分之一或者最小为300K，先到先为准的情况下，
		// 调整至最小为1M并且压缩率最高为10%，先到先为准的情况下，
		while (baos.toByteArray().length / 1024 > 512 && options > 10) {
			Lg.print("baos.toByteArray().length / 1024===" + baos.toByteArray().length / 1024);
			Lg.print("options===" + options);
			baos.reset();
			options -= 10;
			bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
		}
		try {
			FileOutputStream fos = new FileOutputStream(strImgPath);
			fos.write(baos.toByteArray());
			fos.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bmp;
	}

	protected void uninstallAPK(String packageName) {
		Uri uri = Uri.parse("package:" + packageName);
		Intent intent = new Intent(Intent.ACTION_DELETE, uri);
		this.startActivity(intent);
	}

	protected void uninstallAPK() {
		Uri uri = Uri.parse("package:" + getPackageInfo().packageName);
		Intent intent = new Intent(Intent.ACTION_DELETE, uri);
		this.startActivity(intent);
	}

	/**
	 * 获取当前程序的版本号 　　
	 */
	public PackageInfo getPackageInfo() {
		// 获取packagemanager的实例
		PackageManager packageManager = getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = null;
		try {
			packInfo = packageManager.getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return packInfo;
	}

	public ArrayList<PackageInfo> getPackageInfosByLocalApp() {
		PackageManager packageManager = getPackageManager();
		final List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
		ArrayList<PackageInfo> local_pkgInfoNoSys = new ArrayList<PackageInfo>();
		for (int i = 0; i < packageInfos.size(); i++) {
			PackageInfo packageInfo = packageInfos.get(i);
			// 获取 非系统的应用
			if ((packageInfo.applicationInfo.flags & packageInfo.applicationInfo.FLAG_SYSTEM) <= 0) {
				local_pkgInfoNoSys.add(packageInfo);
			}
			// 本来是系统程序，被用户手动更新后，该系统程序也成为第三方应用程序了
			else if ((packageInfo.applicationInfo.flags & packageInfo.applicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
				local_pkgInfoNoSys.add(packageInfo);
			}
		}
		return local_pkgInfoNoSys;
	}

	/**
	 * 判断有无sd卡
	 */
	public boolean hasSdcard() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED) || status.equals("/mnt/sdcard")) {
			return true;
		} else {
			return false;
		}
	}

	public void setTitle(String title) {
		navigationBar.titleText.setText(title);
	}

	/**
	 * UI交互 控制
	 */
	private ArrayList<View> itViews = new ArrayList<View>();

	protected void configViewInteraction(View... v) {
		if (v == null)
			return;
		itViews.clear();
		// fore
	}

	protected void openViewInteraction() {

	}

	protected void closeViewInteraction() {

	}

	/**
	 * 跳船activity 前保存当前activity 的title
	 */
	public static String backActivityTitle = "";
	public View bodyView;
	private int modalAnimTime = 300;
	private boolean isModalFragmentDisplay;

	public void setBackText(String s) {
		backText = s;
	}

	public void pushActivity(Class<?> mClass) {
		if (isEmpty(backText) && navigationBar != null) {
			backActivityTitle = navigationBar.titleText.getText().toString().trim();
		} else {
			backActivityTitle = backText;
		}
		startActivity(new Intent(this, mClass));
	}

	/**
	 * 
	 * {@inheritDoc}
	 * @see cn.android_mobile.core.IBasicCoreMethod#pushActivity(android.content.Intent)
	 */
	public void pushActivity(Intent intent) {
		if (isEmpty(backText) && navigationBar != null) {
			backActivityTitle = navigationBar.titleText.getText().toString().trim();
		} else {
			backActivityTitle = backText;
		}
		startActivity(intent);
	}

	public void pushActivityForResult(Class<?> mClass, int requestCode) {
		if (isEmpty(backText) && navigationBar != null) {
			backActivityTitle = navigationBar.titleText.getText().toString().trim();
		} else {
			backActivityTitle = backText;
		}
		startActivityForResult(new Intent(this, mClass), requestCode);
	}

	public void pushActivityForResult(Intent intent, int requestCode) {
		if (isEmpty(backText) && navigationBar != null) {
			backActivityTitle = navigationBar.titleText.getText().toString().trim();
		} else {
			backActivityTitle = backText;
		}
		startActivityForResult(intent, requestCode);
	}

	public void pushActivity(Class<?> mClass, boolean finishSelf) {
		pushActivity(mClass);
		if (finishSelf) {
			backActivityTitle = "";
			this.finish();
		}
	}
	
	public void pushActivity(Intent intent, boolean finishSelf) {
		pushActivity(intent);
		if (finishSelf) {
			backActivityTitle = "";
			this.finish();
		}
	}

	public void setRootFragmentView(int layoutId) {
		fragmentBodyLayoutRes = layoutId;
	}

	public void pushFragment(BasicFragment f) {
		pushFragment(f, false);
	}

	public void pushFragment(int layoutId, BasicFragment f) {
		pushFragment(layoutId, f, false);
	}

	/**
	 * 初始化Fragment
	 * @param f
	 * @param isUpdateView 是否更新Fragment
	 */
	public void initModalFragment(BasicFragment f, boolean isUpdateView) {
		pushFragment(R.id.frame_modal_view_root, f, false, isUpdateView);
	}

	@Override
	public void pushFragment(BasicFragment f, boolean flag) {
//		if (currentFragment != null && f != null && f.name.equals(currentFragment.name))
//			return;
		FragmentTransaction ft = this.fm.beginTransaction();
		if (this.fragmentChangeEffect) {
			ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_out,
					android.R.anim.fade_in);
		}
		ft.replace(fragmentBodyLayoutRes, f);
		if (flag) {
			ft.addToBackStack(f.name);
		} else {
		}
		ft.commit();
	}

	@Override
	public void pushFragment(int layoutId, BasicFragment f, boolean flag) {
//		if (currentFragment != null && f != null && f.name.equals(currentFragment.name))
//			return;
		FragmentTransaction ft = this.fm.beginTransaction();
		if (this.fragmentChangeEffect) {
			ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_out,
					android.R.anim.fade_in);
		}
		ft.replace(layoutId, f);
		if (flag) {
			ft.addToBackStack(f.name);
		}
		ft.commit();
	}

	public void pushFragment(int layoutId, BasicFragment f, boolean flag, boolean isUpdateView) {
		if(isUpdateView) {
			FragmentTransaction ft = this.fm.beginTransaction();
			if (this.fragmentChangeEffect) {
				ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_out,
						android.R.anim.fade_in);
			}
			ft.replace(layoutId, f);
			if (flag) {
				ft.addToBackStack(f.name);
			}
			ft.commit();
		} else {
			pushFragment(layoutId, f, flag);
		}
	}

	public void popFragment() {
		Lg.print("popFragment");
		if (fm.getBackStackEntryCount() > 1) {
			fm.popBackStack();
		} else {
			popActivity();
		}
	}

	/**
	 * 关闭系统浏览器
	 * 
	 * @return
	 */
	public boolean closeAppWithPackageName(String pkgn) {
		String result = null;
		CMDExecute cmdexe = new CMDExecute();
		try {
			Runtime.getRuntime().exec("su");
			String[] args = { "adb", "shell", "pgrep", pkgn, "|", "xargs", "kill", "-9" };// "com.android.browser"
			result = cmdexe.run(args, "/sdcard/baidu");
			// Lg.print("com.android.browser   PID: "+result.trim());
			// String[] args2 = { "adb","shell", "kill","-9",result.trim()};
			// result = cmdexe.run(args2, "/sdcard/baidu");
			// Lg.print(result);
			toast(result.trim());
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		if (result.indexOf("Success") != -1) {
			return true;
		} else {
			return false;
		}
	}

	public void popActivity() {
		//不是首页的话，则关闭
//		if (!BasicApplication.activityStack.peek().getClass().getName().equals("cn.kkcar.fragments.main.MainActivity")) {
			BasicApplication.activityStack.pop().finish();			
//		}
	}

	/**
	 * 验证日期 是否 低于 今天， 返回Bool
	 * 
	 * @param date
	 * @return
	 */
	public BasicActivity getActivity() {
		return this;
	}

	public boolean validDate(String date) {
		String[] ss = date.split("-");
		int sYear = Integer.parseInt(ss[0]);
		int sMonth = Integer.parseInt(ss[1]);
		int sDay = Integer.parseInt(ss[2]);
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH) + 1;
		int day = cal.get(Calendar.DAY_OF_MONTH);
		// Lg.print(year + "=" + month + "=" + day);
		if (sYear >= year && sMonth >= month && sDay >= day) {
			return true;
		}
		return false;
	}

	@Override
	public void focus(View v) {
		v.setFocusable(true);
		v.setFocusableInTouchMode(true);
		v.requestFocus();
	}

	@Override
	public void displayViewAnimation(View v, int fx, float depth) {
		// right
		if (fx == 1) {
			ObjectAnimator.ofFloat(v, "translationX", SCREEN_WIDTH, SCREEN_WIDTH - depth).start();
		}
	}

	@Override
	public void pushModalFragment(BasicFragment f) {
		this.pushModalFragment(ModalDirection.RIGHT, (int) (SCREEN_WIDTH / 2), modalAnimTime, f);

	}

	@Override
	public void pushModalFragment(int widthDip, BasicFragment f) {
		this.pushModalFragment(ModalDirection.RIGHT, widthDip, modalAnimTime, f);
	}

	@Override
	public void pushModalFragment(ModalDirection d, int widthDip, BasicFragment f) {
		this.pushModalFragment(d, widthDip, modalAnimTime, f);
	}

	public void initModalFragment(BasicFragment f) {
		pushFragment(R.id.frame_modal_view_root, f, false);
	}

	/**
	 * 显示Fragment
	 * @param d
	 * @param widthDip
	 * @param f
	 * @param isUpdateView 再次调用此方法时，是否更新界面
	 */
	public void pushModalFragment(ModalDirection d, int widthDip, BasicFragment f, boolean isUpdateView) {
		initModalFragment(f, isUpdateView);
		pushModalFragment(d, widthDip, modalAnimTime);
	}
	
	@Override
	public void pushModalFragment(ModalDirection d, int widthDip, int time, BasicFragment f) {
		initModalFragment(f);
		pushModalFragment(d, widthDip, time);
	}

	public void pushModalFragment(ModalDirection d, int widthDip, int time) {
		isModalFragmentDisplay = true;
		this.widthDip = widthDip;
		this.modalAnimTime = time;
		this.direction = d;
		modalViewGroupBg.setVisibility(View.VISIBLE);
		modalViewGroup.setVisibility(View.VISIBLE);
		ValueAnimator colorAnim = ObjectAnimator.ofInt(modalViewGroupBg, "backgroundColor", /* Red */0x00000000, /* Blue */
				0x55000000);
		colorAnim.setDuration(modalAnimTime);
		colorAnim.setEvaluator(new ArgbEvaluator());
		colorAnim.start();
		// AnimatorSet set = new AnimatorSet();
		// set.playTogether(
		// ObjectAnimator.ofFloat(modalViewGroup, "translationX", SCREEN_WIDTH,
		// SCREEN_WIDTH-widthDip)
		// );
		RelativeLayout.LayoutParams imagebtn_params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		if (ModalDirection.RIGHT == d) {
			// Lg.print("modal  right");
			imagebtn_params.height = (int) SCREEN_HEIGHT;
			imagebtn_params.width = widthDip;
			modalViewGroup.setLayoutParams(imagebtn_params);
			ObjectAnimator.ofFloat(modalViewGroup, "translationX", SCREEN_WIDTH, SCREEN_WIDTH - widthDip)
					.setDuration(modalAnimTime).start();

		} else if (ModalDirection.LEFT == d) {
			// Lg.print("modal  left");
			imagebtn_params.height = (int) SCREEN_HEIGHT;
			imagebtn_params.width = widthDip;
			modalViewGroup.setLayoutParams(imagebtn_params);
			ObjectAnimator.ofFloat(modalViewGroup, "translationX", -widthDip, 0).setDuration(modalAnimTime).start();
		} else if (ModalDirection.BOTTOM == d) {
			// Lg.print("modal  bottom");
			imagebtn_params.height = widthDip;
			imagebtn_params.width = (int) SCREEN_WIDTH;
			modalViewGroup.setLayoutParams(imagebtn_params);
			ObjectAnimator
					.ofFloat(modalViewGroup, "y", SCREEN_HEIGHT - getStatusBarHeight(),
							SCREEN_HEIGHT - getStatusBarHeight() - widthDip).setDuration(modalAnimTime).start();
		} else if (ModalDirection.TOP == d) {
			// Lg.print("modal  top");
			imagebtn_params.height = widthDip;
			imagebtn_params.width = (int) SCREEN_WIDTH;
			modalViewGroup.setLayoutParams(imagebtn_params);
			int titleBarHeight = navigationBar.getNavigationBarHeight() * 2 + 3;
			ObjectAnimator.ofFloat(modalViewGroup, "translationY", -widthDip, titleBarHeight).setDuration(modalAnimTime).start();
		}
		// pushFragment(R.id.frame_modal_view_root, f,false);
	}

	@Override
	public void pushModalView(View v, ModalDirection d, int widthDip, int time) {
		modalViewGroup.removeAllViews();
		RelativeLayout.LayoutParams vLp = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		modalViewGroup.addView(v, vLp);
		isModalFragmentDisplay = true;
		this.widthDip = widthDip;
		this.modalAnimTime = time;
		this.direction = d;
		modalViewGroupBg.setVisibility(View.VISIBLE);
		modalViewGroup.setVisibility(View.VISIBLE);
		ValueAnimator colorAnim = ObjectAnimator.ofInt(modalViewGroupBg, "backgroundColor", /* Red */0x00000000, /* Blue */
				0x55000000);
		colorAnim.setDuration(modalAnimTime);
		colorAnim.setEvaluator(new ArgbEvaluator());
		colorAnim.start();
		RelativeLayout.LayoutParams imagebtn_params = (android.widget.RelativeLayout.LayoutParams) modalViewGroup
				.getLayoutParams();
		if (ModalDirection.RIGHT == d) {
			// Lg.print("modal  right");
			imagebtn_params.height = (int) SCREEN_HEIGHT;
			imagebtn_params.width = widthDip;
			modalViewGroup.setLayoutParams(imagebtn_params);
			ObjectAnimator.ofFloat(modalViewGroup, "translationX", SCREEN_WIDTH, SCREEN_WIDTH - widthDip)
					.setDuration(modalAnimTime).start();

		} else if (ModalDirection.LEFT == d) {
			// Lg.print("modal  left");
			imagebtn_params.height = (int) SCREEN_HEIGHT;
			imagebtn_params.width = widthDip;
			modalViewGroup.setLayoutParams(imagebtn_params);
			ObjectAnimator.ofFloat(modalViewGroup, "translationX", -widthDip, 0).setDuration(modalAnimTime).start();
		} else if (ModalDirection.BOTTOM == d) {
			// Lg.print("modal  bottom: STATUS BAR HEIGHT:" +
			imagebtn_params.height = widthDip;
			imagebtn_params.width = (int) SCREEN_WIDTH;
			modalViewGroup.setLayoutParams(imagebtn_params);
			ObjectAnimator
			.ofFloat(modalViewGroup, "y", SCREEN_HEIGHT - getStatusBarHeight(),
					SCREEN_HEIGHT - getStatusBarHeight() - widthDip).setDuration(modalAnimTime).start();
			
		} else if (ModalDirection.TOP == d) {
			// Lg.print("modal  top");
			imagebtn_params.height = widthDip;
			imagebtn_params.width = (int) SCREEN_WIDTH;
			modalViewGroup.setLayoutParams(imagebtn_params);
			ObjectAnimator.ofFloat(modalViewGroup, "y", -widthDip, 0).setDuration(modalAnimTime).start();
		} else if (ModalDirection.TOP_BOTTOM == d){
			//顶部延伸至底部
			imagebtn_params.height = widthDip;
			imagebtn_params.width = (int) SCREEN_WIDTH;
			modalViewGroup.setLayoutParams(imagebtn_params);
			int titleBarHeight = navigationBar.getNavigationBarHeight();
			ObjectAnimator.ofFloat(modalViewGroup, "y", widthDip + titleBarHeight, titleBarHeight).setDuration(modalAnimTime).start();
		}
	}

	@Override
	public void pushModalView(View v, ModalDirection d, int widthDip) {
		pushModalView(v, d, widthDip, modalAnimTime);
	}

	@Override
	public void pushModalView(View v, int widthDip) {
		pushModalView(v, ModalDirection.BOTTOM, widthDip, modalAnimTime);
	}

	public static int skinColor = -1;

	public void updateSkin(int skinColor) {
		if (skinColor != -1) {
			navigationBar.layout.setBackgroundColor(skinColor);
			// bodyView.setBackgroundColor(skinColor);
			BasicEvent e = new BasicEvent(BasicEvent.UPDATE_SKIN);
			e.setData(skinColor);
			dispatchBasicEvent(e);
			CacheUtil.saveInteger("SKIN_COLOR", skinColor);
		}
	}

	@Override
	public void setSkin(String color) {
		skinColor = Color.parseColor(color);
		updateSkin(skinColor);
	}

	@Override
	public boolean hasSkinColor() {
		if (skinColor == -1) {
			return false;
		}
		return true;
	}

	@Override
	public void setSkin(int colorRes) {
		skinColor = colorRes;
		updateSkin(skinColor);
	}

	@Override
	public void popModalView() {
		popModalFragment();
	}

	@Override
	public void popModalFragment() {
		isModalFragmentDisplay = false;
		if (direction == ModalDirection.RIGHT) {
			ObjectAnimator.ofFloat(modalViewGroup, "translationX", SCREEN_WIDTH - widthDip, SCREEN_WIDTH)
					.setDuration(modalAnimTime).start();
		} else if (direction == ModalDirection.LEFT) {
			ObjectAnimator.ofFloat(modalViewGroup, "translationX", 0, -widthDip).setDuration(modalAnimTime).start();
		} else if (direction == ModalDirection.TOP) {
			ObjectAnimator.ofFloat(modalViewGroup, "y", 0, -widthDip).setDuration(modalAnimTime).start();
		} else if (direction == ModalDirection.BOTTOM) {
			ObjectAnimator
					.ofFloat(modalViewGroup, "y", SCREEN_HEIGHT - widthDip - getStatusBarHeight(),
							SCREEN_HEIGHT - getStatusBarHeight()).setDuration(modalAnimTime).start();
		} else if(direction == ModalDirection.TOP_BOTTOM) {
			int titleBarHeight = navigationBar.getNavigationBarHeight();
			ObjectAnimator.ofFloat(modalViewGroup, "y", titleBarHeight, widthDip + titleBarHeight).setDuration(modalAnimTime).start();
		}
		ValueAnimator colorAnim = ObjectAnimator.ofInt(modalViewGroupBg, "backgroundColor", /* Red */
				0x55000000, /* Blue */0x00000000);
		colorAnim.setDuration(modalAnimTime);
		colorAnim.setEvaluator(new ArgbEvaluator());
		colorAnim.addListener(new AnimatorListenerAdapter() {
			@Override
			public void onAnimationEnd(Animator animation) {
				super.onAnimationEnd(animation);
				modalViewGroupBg.setVisibility(View.GONE);
				modalViewGroup.setVisibility(View.GONE);
			}

			@Override
			public void onAnimationStart(Animator animation) {
				super.onAnimationStart(animation);
			}
		});
		colorAnim.start();
	}

	@Override
	public void addBasicEventListener(String type, IBasicListener listener) {
		BasicEventDispatcher.addEventListener(this.getClass().getName(), type, listener);
	}

	@Override
	public void dispatchBasicEvent(BasicEvent e) {
		BasicEventDispatcher.dispatcher(e);
	}

	@Override
	public void removeBasicEvent() {
		BasicEventDispatcher.removeEventListenerByKey(this.getClass().getName());
	}

	/**
	 * Object 可以为View（View） int（ResID） 或者 String（url）
	 */
	private Stack<Integer> helpImgs = new Stack<Integer>();
	public Stack<Integer> helpFragmentImgs = new Stack<Integer>();

	private Bitmap displayHelpView(int resId) {
		helpView.removeAllViews();
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
				RelativeLayout.LayoutParams.MATCH_PARENT);
		ImageView imageView = new ImageView(this);
		Bitmap b = readBitmap(resId);
		imageView.setScaleType(ScaleType.FIT_XY);
		imageView.setImageBitmap(b);
		helpView.addView(imageView, lp);
		helpView.bringToFront();
		helpView.setVisibility(View.VISIBLE);
		return b;
	}

	@Override
	public void displayHelpView(Integer... resIds) {
		if (isFirstViewRunning() == false) {
			return;
		}
		for (int i = resIds.length - 1; i >= 0; i--) {
			helpImgs.add(resIds[i]);
		}
		displayHelpView(helpImgs.pop());
	}

	@Override
	public int getSkinColor() {
		return skinColor;
	}

	@Override
	public void startWebBrowser(String url) {
		Uri uri = Uri.parse(url);
		Intent it = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(it);
	}

	@Override
	public boolean isTestUser(String phone) {
		if (phone.startsWith("400")) {
			return true;
		}
		return false;
	}

	@Override
	public boolean isFirstAppRunning() {
		boolean b = true;
		if (CacheUtil.getInteger("app_help_view") < 0) {
			b = true;
		} else {
			b = false;
		}
		CacheUtil.saveInteger("app_help_view", 100);
		// Lg.print("App是否第一次运行：" + b);
		return b;
	}

	@Override
	public boolean isFirstViewRunning() {
		boolean b = true;
		if (CacheUtil.getInteger("app_help_view" + this.getClass().getName()) < 0) {
			b = true;
		} else {
			b = false;
		}
		CacheUtil.saveInteger("app_help_view" + this.getClass().getName(), 100);
		// Lg.print("Acitivy是否第一次运行：" + b);
		return b;
	}

	// 友盟 session的统计 获取正确的新增用户、活跃用户、启动次数、使用时长等基本数据
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		if (Lg.DEBUG) {
			ViewServer.get(this).setFocusedWindow(this);
		}
	}

	// 判断设备有无拨打电话功能
	protected boolean isIntentAvailable(Intent intent) {
		PackageManager packageManager = getPackageManager();
		List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
		return list.size() > 0;
	}

	@Override
	public void startPhoneCall(String phoneNum) {
		if (isEmpty(phoneNum))
			return;
		// 调用拨打电话页面，android.intent.action.Call直接调用拨打电话。
		Intent intent = new Intent();
		intent.setAction("android.intent.action.DIAL");
		intent.setData(Uri.parse("tel:" + phoneNum));
		if (isIntentAvailable(intent)) {
			startActivity(intent);
		} else {
			toast("没有拨打电话功能");
		}
	}

	@Override
	public int getStatusBarHeight() {
		Rect frame = new Rect();
		getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
		int statusBarHeight = frame.top;
		// Class<?> c = null;
		// Object obj = null;
		// Field field = null;
		// int x = 0, statusBarHeight = 0;
		// try {
		// c = Class.forName("com.android.internal.R$dimen");
		// obj = c.newInstance();
		// field = c.getField("status_bar_height");
		// x = Integer.parseInt(field.get(obj).toString());
		// statusBarHeight = this.getResources().getDimensionPixelSize(x);
		// } catch (Exception e1) {
		// e1.printStackTrace();
		// }
		return statusBarHeight;
	}

	@Override
	public Bitmap readBitmap(int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		// opt.inSampleSize =2;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (Lg.DEBUG) {
			ViewServer.get(this).removeWindow(this);
		}
	}

	@Override
	public Bitmap readBitmap(String path) {
		return myImageCompress(path);
	}

}
